<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Admin\AdminLogModel;
use App\Services\Admin\AdminService;
use Illuminate\Http\Request;
use Session;
use Hash;

class LoginController extends BaseController
{
    /**
     * 登陆
     */

    public function __construct()
    {
        parent::__construct();
        define('ADMIN_DOMAIN',DOMAIN.'/mcadmin');
        define('PUB_ADMIN_DOMAIN',DOMAIN.'/assets-admin/');
        $this->model = new AdminService();
    }

    public function login()
    {
        return view('admin.login');
    }

    public function doLogin(Request $request)
    {
        $name = $request->name;
        $pwd = $request->pwd;
        $model = $this->model->getOneAdmin($name);
        if (!$model) {
            echo "<script>alert('该管理员不存在！');history.go(-1);</script>"; exit;
        }
        if (!(Hash::check($pwd,$model->pwd))) {
            echo "<script>alert('密码错误！');history.go(-1);</script>"; exit;
        }
        $sessArr = array(
            'id' => $model->id,
            'name' => $model->name,
            'createTime' => time(),
        );
        Session::put('admin',$sessArr);
        //登陆日志
        AdminLogModel::create(array(
            'admin' => $model->id,
            'loginTime' => time(),
        ));
        return redirect(ADMIN_DOMAIN);
    }

    public function doLogout()
    {
        if (!Session::has('admin')) {
            echo "<script>alert('没有登陆！');history.go(-1);</script>"; exit;
        }
        $sess = Session::get('admin');
        Session::forget('admin');
        AdminLogModel::where('id',$sess['id'])->update(array('logoutTime'=>time()));
        return redirect(ADMIN_DOMAIN.'/login');
    }
}